const app = getApp();
const that=this;
const db=wx.cloud.database('');
const articles=db.collection('articles');
const articlePhotos=db.collection('articlePhotos');
const util=require('../../../utils/utils.js');
Page({
  data: {
    articleTitle: "",
    articleCover:[],
    formats: {},
    readOnly: false,   //设置编辑器微只读read-only
    placeholder: '请输入...',
    articleContent:"",   //文章的内容
    describeContent:"",     //文章描述内容
    keyboardHeight: 0,//键盘高度
    isIOS: false,
    active: 0
  },
  // 分页
  onChange(event) {
    wx.showToast({
      title: `切换到标签 ${event.detail.name}`,
      icon: 'none',
    });
  },
  /**
   * 自定义函数-----------文章标题改变时候触发
   */
  onArticleTitleChange:function(e) {
    this.setData({
      articleTitle: e.detail
    })
  },
  /**
   * 自定义函数--------------删除上传图片的时候触发
   */
  //删除
  delCover:function(e) {
    this.setData({
      articleCover:[]
    })
  },
  // 上传
  uploadCover: function(event) {
    const {file}=event.detail;
    console.log(event.detail.file.path);//触发文件上传事件
    const filePath = file.path;
    const cloudPath = 'Tec微社区文章图片/'+Math.floor(Math.random()*1000000)+filePath.match(/\.[^.]+?$/)[0];
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        console.log('[上传文件] 成功：', res);
        this.setData({
          articleCover: [{
            url: res.fileID
          }]
        });
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
/**
 * 自定义函数-----------------文章的编辑
 */
//对富文本编辑进行初始化
onEditorReady: function() {
  const that = this;
  wx.createSelectorQuery().select('#editor').context(function (res) {
    that.editorCtx = res.context
  }).exec()
},
/**
 * 声明周期函数---------监听页面加载
 */
readOnlyChange :function() {
  this.setData({
    readOnly: !this.data.readOnly
  })
},
onLoad:function() {
  //判断平台
  const platform = wx.getSystemInfoSync().platform
  const isIOS = platform === 'ios'
  this.setData({ isIOS})
  const that = this
  this.updatePosition(0)
  let keyboardHeight = 0
  wx.onKeyboardHeightChange(res => {
    if (res.height === keyboardHeight) return
    const duration = res.height > 0 ? res.duration * 1000 : 0
    keyboardHeight = res.height
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 0,
        success() {
          that.updatePosition(keyboardHeight)
          that.editorCtx.scrollIntoView()
        }
      })
    }, duration)
  })
},
//更新位置
updatePosition(keyboardHeight) {
  const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
},
//导航条的状态
calNavigationBarAndStatusBar() {
  const systemInfo = wx.getSystemInfoSync()
  const { statusBarHeight, platform } = systemInfo
  const isIOS = platform === 'ios'
  const navigationBarHeight = isIOS ? 44 : 48
  return statusBarHeight + navigationBarHeight
},
//聚焦
blur() {
  this.editorCtx.blur()
},
//形式
format(e) {
  let { name, value } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)
},
//editor状态改变的时候
onStatusChange(e) {
  const formats = e.detail
  this.setData({ formats })
},
//插入分割线
insertDivider() {
  this.editorCtx.insertDivider({
    success: function () {
      console.log('insert divider success')
    }
  })
},
//清除
clear() {
  this.editorCtx.clear({
    success: function (res) {
      console.log("clear success")
    }
  })
},
//移除形式
removeFormat() {
  this.editorCtx.removeFormat()
},
//插入日期
insertDate() {
  const date = new Date()
  const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
  this.editorCtx.insertText({
    text: formatDate
  })
},
//插入图片
insertImage() {
  const that = this;
    wx.chooseImage({
      count: 6,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath=res.tempFilePaths[0]; //获取图片临时地址
        console.log(filePath);
        const cloudPath=Math.floor(Math.random()*1000000)+filePath.match(/.[^.]+?$/)[0];//自定义云端的图片名称
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success:res=>{
            that.editorCtx.insertImage({
              src:res.fileID,
              width:'80%',
              success:res=>{
                console.log('insert image success');        
              }
            });
            articlePhotos.add({
              data:{
                photoUrl:res.fileID
              },
              success:res=>{
                  console.log('图片上传成功！')
              },
              fail:err=>{
                console.log('图片上传失败！'+err);
              }
            })
          },
          fail:err=>{
            console.log('上传文件失败'+err);
          }
        })
        // that.editorCtx.insertImage({
        //   src: res.tempFilePaths[0],
        //   data: {
        //     id: 'abcd',
        //     role: 'god'
        //   },
        //   width: '80%',
        //   success: function () {
        //     console.log('insert image success')
        //   }
        // })
      }
    })
},
//这个是富文本
onArticleContentChange(e) {
    this.setData({
      articleContent: e.detail.html
    })
  },
//文章描述内容改变时触发
articleDescribe(e){
  this.setData({
    describeContent:e.detail
  })
},
//点击按钮发布文章
  saveArticle: function(event) {
    if (!this.data.articleTitle) {
      wx.showToast({
        title: '文章标题不能为空',
      })
      return
    }
    if (!this.data.articleContent) {
      wx.showToast({
        title: '文章内容不能为空',
      })
      return
    }
    if (!this.data.describeContent) {
      wx.showToast({
        title: '文章描述内容不能为空',
      })
      return
    }
    if (!this.data.articleCover.length==1) {
      wx.showToast({
        title: '上传图片不能为空',
      })
      return
    }
    if (!this.data.articleId) {//这个地方有待改进，初始写文章的时候都为空
      this.addArticle();
    } else {
      this.updateArticle();//这里就没有设计文章保存功能所以要怎么进行文章更新呢？？？？？？改进中
    }
  },
  // 添加文章
  addArticle:function() {
    let today=util.formatDate();
    wx.showToast({
      title: '正在发布中',
      icon: 'loading'
    });
    
    wx.cloud.callFunction({
      name:'getOpenid',
      complete:res=>{
        articles.add({
          data: {
            articleId:Math.floor(Math.random()*1000000)+'0',
            openid:res.result.openid,
            title: this.data.articleTitle,
            cover: this.data.articleCover[0].url,
            content: this.data.articleContent,
            describe:this.data.describeContent,
            avatarUrl:app.globalData.userInfo.avatarUrl,
            nickName:app.globalData.userInfo.nickName,
            time:today,
            commentNum:0,
            likeNum:0,
            collectNum:0,
            articleSummry:"",
          },
          success: res => {
            wx.showToast({
              title: '发布成功',
            });
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2];
            wx.navigateBack({
              delta: 1,
              success: function() {
                if (prevPage.route == 'pages/home/home') {
                  prevPage.loadData();
                }
              }
            })
          },
          fail: err => {
            wx.showToast({
              icon: 'none',
              title: '发布失败'
            })
          }
        })
      }
    })
  } 
})